<?php defined('SYSPATH') or die('No direct script access.');

// URL: /<context>/index.php/Home/
class Controller_Connection extends Controller_Base 
{
	protected $categoryService;
	protected $relationService;
	protected $followingService;
	
	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		$this->categoryService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_CATEGORY.'/', ACCESS_TOKEN);
		$this->categoryService->init($this->_requestContext);
		
		$this->relationService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_RELATION.'/', ACCESS_TOKEN);
		$this->relationService->init($this->_requestContext);
		
		$this->followingService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_FOLLOWING.'/', ACCESS_TOKEN);
		$this->followingService->init($this->_requestContext);
	}
	
	public function action_list()
	{
		$this->template->title = __('Seednia::Relation');

		$myselfSid = -1;
		if ($this->_sessionInfo->userInfo['userSid'] > 0) {
			$myselfSid = $this->_sessionInfo->userInfo['userSid'];
		} else {
			//$ownerSid
		}

		$content = View::factory($this->_theme.'/relation_list');

		try {
			$relationCriteria = array('creatorSid' => $myselfSid);
			$content->relations = $this->relationService->getList($relationCriteria, 0, 10);
			//echo Debug::vars($content->relations);
			$this->template->content = $content;

		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add Lis | Message: ' . $ex->getMessage());
		}
	}
	
	/**
	 * Invite a user 
	 */
	public function action_invite()
	{
		try {
			$creatorSid = $this->_sessionInfo->userInfo['userSid'];
			$coUserSid = $this->request->query('coUserSid');
			$description = $this->request->post('description');
			$kind = $this->request->post('kind');
			if ($kind == null ) $kind = 'following';

			$redirTo = CONTROLLERPAGE.'/home';
			$params = array('creatorSid'=>$creatorSid
				, 'coUserSid' => $coUserSid, 'kind' => $kind, 'description'=>$description);
			$sid = $this->relationService->add($params);

			if ($sid != null) {
				; // TODO: handle error
			}

			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	/**
	 * Accept an invitation with the access code 
	 */
	public function action_accept()
	{
		
	}
	
	/**
	 * Follow a project/person 
	 * Later change this to AJAX
	 */
	public function action_follow()
	{
		
		$fields['targetType'] = $this->request->get('targetType');
		$fields['targetSid'] = $this->request->get('targetSid');
		
		$this->followingService->add($fields);
		
		// TODO: change below address
		$redirTo = CONTROLLERPAGE.'/Home';
		$this->request->redirect($redirTo);
	}
	
} // End Controller_Home